package cn.earl.springboot.user.controller;

import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.earl.springboot.entity.Demand;
import cn.earl.springboot.entity.DemandType;
import cn.earl.springboot.entity.ResponseMessage;
import cn.earl.springboot.user.service.DemandService;

/**
 * 用户功能
 * 
 * @author ASUS-A455L
 *
 */
@RestController
@RequestMapping("/user")
public class UserFunction {

	@Autowired
	private DemandService demandService;
	@Autowired
	private MessageSource messageSource;

	/**
	 * 发布需求
	 * 
	 * @param demand
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping("/publish")
	public ResponseMessage<String> publish(@Validated Demand demand, BindingResult bindingResult) {

		// 提取错误信息并返回
		if (bindingResult.hasErrors()) {
			StringBuffer error = new StringBuffer();

			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			Locale locale = LocaleContextHolder.getLocale();

			for (FieldError fe : fieldErrors) {
				String message = messageSource.getMessage(fe, locale);
				error.append(fe.getField() + "：" + message);
			}
			return new ResponseMessage<>(200, error.toString());
		}
		demandService.save(demand);

		return new ResponseMessage<>(250, "发布成功");

	}
}
